package com.mall507.fivepeaks.activity;


import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.activeandroid.query.Delete;
import com.activeandroid.query.Select;
import com.facebook.drawee.view.SimpleDraweeView;
import com.hzh.frame.comn.annotation.ContentView;
import com.hzh.frame.comn.annotation.OnClick;
import com.hzh.frame.comn.annotation.SelectTable;
import com.hzh.frame.comn.annotation.ViewInject;
import com.hzh.frame.comn.callback.HttpCallBack;
import com.hzh.frame.comn.model.BaseHttpRequest;
import com.hzh.frame.core.BaseSP;
import com.hzh.frame.core.HttpFrame.BaseHttp;
import com.hzh.frame.core.ImageFrame.BaseImage;
import com.hzh.frame.ui.activity.BaseUI;
import com.hzh.frame.util.CloseAppUtil;
import com.hzh.frame.util.FileUtil;
import com.mall507.comn.model.MapUtil;
import com.mall507.comn.model.User;
import com.mall507.comn.model.WelcomeAd;
import com.mall507.comn.tools.UserTools;
import com.mall507.fivepeaks.R;
import com.mall507.fivepeaks.widget.xwebview.XWebViewToMainActivity;
import com.mall507.fivepeaks.util.Util;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

@ContentView(R.layout.ui_welcome)
public class WelcomeUI extends BaseUI {

    @ViewInject(R.id.iv_welcome)
    ImageView mImageView;
    @ViewInject(R.id.welcomeAd)
    SimpleDraweeView welcomeAd;
    @ViewInject(R.id.adText)
    TextView adText;
    @ViewInject(R.id.adTime)
    LinearLayout adTime;

    @Override
    public boolean setTitleIsShow() {
        return false;
    }

    @Override
    protected void onCreateBase() {
        new Delete().from(BaseHttpRequest.class).execute();
        BaseSP.getInstance().put("firstAward", true);
        loadWelcomeAd();
        getValue();
        findView();
        init();
    }


    private void findView() {
        LayoutParams lpAdText = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        lpAdText.topMargin = Util.dip2px(this, 10);
        lpAdText.leftMargin = Util.dip2px(this, 10);
        adText.setLayoutParams(lpAdText);
        adText.setGravity(Gravity.CENTER);
        adText.setVisibility(View.GONE);
        LayoutParams lpAdTime = new LayoutParams(Util.dip2px(this, 45), Util.dip2px(this, 45), Gravity.RIGHT);
        lpAdTime.topMargin = Util.dip2px(this, 10);
        lpAdTime.rightMargin = Util.dip2px(this, 10);
        adTime.setLayoutParams(lpAdTime);
        adTime.setGravity(Gravity.CENTER);
        adTime.setVisibility(View.GONE);
        adTime.setClickable(false);
        Animation ani = new AlphaAnimation(0f, 1f);
        ani.setDuration(1500);
        ani.setRepeatMode(Animation.REVERSE);
        mImageView.startAnimation(ani);
    }

    private boolean flag = true;

    private void init() {
        if (mImageView.getVisibility() == View.VISIBLE) {
            new Handler().post(new Runnable() {
                @Override
                public void run() {
                    final WelcomeAd model = new Select().from(WelcomeAd.class).executeSingle();
                    if (null != model && model.getIsDown() == 1) {
                        BaseImage.getInstance().load("file://" + model.getLocalUrl(), welcomeAd);
                        welcomeAd.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                //广告图片点击
                                if (model.getOnClickUrl() != null && !"".equals(model.getOnClickUrl())) {
                                    flag = false;
                                    if (Util.isNumber(model.getOnClickUrl())) {
                                    } else {
                                        Intent intent = new Intent(WelcomeUI.this, XWebViewToMainActivity.class);
                                        intent.putExtra("url", model.getOnClickUrl());
                                        startActivity(intent);
                                    }
                                    finish();
                                }
                            }
                        });
                        adText.setVisibility(View.VISIBLE);
                        adTime.setVisibility(View.VISIBLE);
                        adTime.setClickable(true);
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if (flag) {
                                    //用户无任何操作,时间到了自动进入APP
                                    Intent intent = new Intent(WelcomeUI.this, MainUI.class);
                                    startActivity(intent);
                                    finish();
                                }
                            }
                        }, 5000);
                    } else {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Intent intent = new Intent(WelcomeUI.this, MainUI.class);
                                startActivity(intent);
                                finish();
                            }
                        }, 2000);
                    }
                }
            });
        }
    }

    @OnClick(R.id.adTime)
    public void adClick(View view) {
        //跳过广告
        flag = false;
        Intent intent = new Intent(WelcomeUI.this, MainUI.class);
        startActivity(intent);
        finish();
    }

    /**
     * 下载广告
     */
    public void loadWelcomeAd() {
        BaseHttp.getInstance().query("", null, new HttpCallBack() {
            @Override
            public void onSuccess(JSONObject response) {
                if (1 == response.optInt("result")) {
                    JSONObject data = response.optJSONObject("data");
                    if (1 == data.optInt("code")) {
                        JSONArray list = data.optJSONArray("ad");
                        if (null != list && list.length() > 0) {
                            WelcomeAd model = new Select().from(WelcomeAd.class).executeSingle();
                            if (model == null) {
                                //本地还没有广告
                                model = new WelcomeAd();
                                model.setOnClickUrl(list.optJSONObject(0).optString("ad_url"));
                                model.setUrl(list.optJSONObject(0).optString("photo_url"));
                                model.setIsDown(0);
                                downPic(model);
                            } else {
                                //本地已有广告
                                if (!model.getUrl().equals(list.optJSONObject(0).optString("photo_url"))) {
                                    //此广告未在本地
                                    new Delete().from(WelcomeAd.class).execute();
                                    model.setOnClickUrl(list.optJSONObject(0).optString("ad_url"));
                                    model.setUrl(list.optJSONObject(0).optString("photo_url"));
                                    model.setIsDown(0);
                                    downPic(model);
                                } else {
                                    if (model.getIsDown() == 1) {
                                        //此广告已经在本地,图片下载到本地SD卡
                                    } else {
                                        //此广告已经在本地,图片未下载到本地SD卡
                                        downPic(model);
                                    }
                                }
                            }
                        } else {
                            //没有广告需要投放删除本地广告
                            new Delete().from(WelcomeAd.class).execute();
                        }
                    }
                }
            }

            @Override
            public void onFail() {
            }
        });
    }

    /**
     * 图片下载
     **/
    public void downPic(final WelcomeAd model) {
        BaseHttp.getInstance().get(model.getUrl(), new HttpCallBack(HttpCallBack.RESPONSE_BYTEARRAY) {
            @Override
            public void onSuccess(byte[] byteArray) {
                String returnPath = FileUtil.saveLocal2ByteArray(byteArray, "WelcomeAd");
                if (!Util.isEmpty(returnPath)) {
                    Log.e("下载首页广告", "-----下载成功------" + returnPath + "-----");
                    model.setIsDown(1);
                    model.setLocalUrl(returnPath);
                    model.save();
                } else {
                    Log.e("下载首页广告", "-----下载失败-----" + returnPath + "-----");
                }
            }
        });
    }
    
    public void getValue(){
        final User user = UserTools.getInstance().getUser();
        user.setValue("0");
        UserTools.getInstance().updUser(user);
        user.save();
        BaseHttp.getInstance().query("config/androidRecruitSwitch", new HttpCallBack() {
            @Override
            public void onSuccess(JSONObject response) {
                super.onSuccess(response);
                if (response.optInt("code") == 200){
                    JSONObject data = response.optJSONObject("data");
                    if (data != null && data.length()>0){
                        user.setValue(data.optString("value"));
                        UserTools.getInstance().updUser(user);
                    }
                }else {
                    User user = new User().setValue("0");
                    UserTools.getInstance().updUser(user);
                }
            }

            @Override
            public void onFailure() {
                super.onFailure();
                User user = new User().setValue("0");
                UserTools.getInstance().updUser(user);
            }
        });
    }
}
